import { Controller, Get, Query, Request, Inject } from '@nestjs/common';
import { RecommendationService } from './recommendation.service';
import { ApiOperation, ApiTags, ApiQuery } from '@nestjs/swagger';
import { Public } from 'src/common/decorators/public';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from 'src/entities/user.entity';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';

@ApiTags('视频推荐')
@Controller('recommendation')
export class RecommendationController {
  constructor(
    private readonly recommendationService: RecommendationService,
    private readonly jwtService: JwtService,
    @InjectRepository(User) private readonly userRepository: Repository<User>,
    @InjectRedis() private readonly redis: Redis,
  ) {}

  @Get('videos')
  @Public()
  @ApiOperation({ summary: '获取推荐视频' })
  @ApiQuery({
    name: 'limit',
    required: false,
    type: Number,
    description: '返回视频数量',
  })
  @ApiQuery({
    name: 'refresh',
    required: false,
    type: Boolean,
    description: '是否强制刷新推荐池',
  })
  async getRecommendedVideos(
    @Request() req,
    @Query('limit') limit: number = 10,
    @Query('refresh') refresh: boolean = false,
  ) {
    let isLoggedIn = false;
    let userId = null;

    // 手动解析token
    const token = this.extractTokenFromHeader(req);

    if (token) {
      // 检查令牌是否在黑名单中
      const isBlacklisted = await this.redis.exists(`user:blacklist:${token}`);

      if (!isBlacklisted) {
        try {
          // 验证并解析令牌
          const payload = this.jwtService.verify(token);

          console.log('Token有效载荷:', payload);

          // 获取用户信息
          const user = await this.userRepository.findOne({
            where: { id: payload.id },
          });

          if (user) {
            isLoggedIn = true;
            userId = user.id;
          }
        } catch (error) {
          console.error('Token验证失败:', error);
        }
      }
    }

    console.log('用户登录状态:', isLoggedIn, '用户ID:', userId);

    // 游客模式: 热门视频 + 随机推送
    let videos = [];
    if (!isLoggedIn) {
      videos = await this.recommendationService.getGuestRecommendations(limit);
    } else {
      // 允许用户强制刷新推荐池
      if (refresh) {
        await this.recommendationService.invalidateRecommendationCache(userId);
      }

      videos = await this.recommendationService.getRecommendedVideos(
        userId,
        limit,
      );
    }

    return {
      code: 200,
      data: videos,
      message: '获取推荐视频成功',
    };
  }

  private extractTokenFromHeader(request: any): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}
